package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.entity.Game;
import org.clipjoint.entity.dto.GameDto;
import org.clipjoint.enums.GameTypeEnum;
import org.clipjoint.service.GameAdminService;
import org.clipjoint.service.impl.GameAdminServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 陈光耀
 * date: 2021-2-22
 */
@WebServlet("/gameadmin")
public class GameAdminController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private GameAdminService gameService = new GameAdminServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        switch (method) {
            case "list":
                list(request, response);
                break;
            case "add":
                add(request, response);
                break;
            case "deleteAll":
                deleteAll(request, response);
                break;
            case "detailGame":
                detailGame(request, response);
                break;
            case "delete":
                delete(request, response);
                break;
            case "updatePage":
                updatePage(request, response);
                break;
            case "update":
                update(request, response);
                break;
            case "createTimeStat":
                createTimeStat(request, response);
                break;

        }

    }


    //游戏数据的统计
    private void createTimeStat(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取需要统计的月份
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM").parse(request.getParameter("date"));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 获取开始时间
        Date createTimeStart = date;
        // 获取结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.MILLISECOND, -1);
        Date createTimeEnd = calendar.getTime();

        // 查询本月发布的游戏数据
        List<Game> games = null;
        try {
            games = gameService.list(GameDto.builder().createTimeStart(createTimeStart).createTimeEnd(createTimeEnd).build());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 日期集合
        List<Integer> days = new ArrayList<>();

        // 游戏集合
        List<Long> counts = new ArrayList<>();

        // 初始化日期集合
        for (int i = 1; i <= calendar.get(Calendar.DAY_OF_MONTH); i++) {
            days.add(i);
        }

        // 初始化游戏集合
        for (int i = 1; i <= calendar.get(Calendar.DAY_OF_MONTH); i++) {
            counts.add(0L);
        }

        // 遍历日期
        for (Integer day : days) {
            // 遍历游戏集合
            for (Game user : games) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(user.getTime());
                int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                if (dayOfMonth == day) {
                    counts.set(day - 1, counts.get(day - 1) + 1);
                }
            }
        }

        // 使用map集合封装结果
        Map<String, Object> map = new HashMap<>();
        map.put("days", days);
        map.put("counts", counts);

        // 返回统计结果
        response.getWriter().print(JsonResult.builder().code(0).data(map).build().toJsonString());


    }


    //对游戏进行编辑
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取请求参数
        Long id = Long.valueOf(request.getParameter("id"));
        String name = request.getParameter("name");
        String nickname = request.getParameter("nickname");
        GameTypeEnum type = GameTypeEnum.valueOf(request.getParameter("type"));
        Double preprice = Double.valueOf(request.getParameter("preprice"));
        Integer off = Integer.valueOf(request.getParameter("off"));
        Double price = Double.valueOf(request.getParameter("price"));
        String content = request.getParameter("content");
        Long credit = Long.valueOf(request.getParameter("credit"));
        String image = request.getParameter("image");
        String system = request.getParameter("system");

        // 将富文本内容中的src地址替换为objectName
//        for (String contentKey : WangEditorController.urlAndObjectNameMap.keySet()) {
//            content = content.replace(contentKey, WangEditorController.urlAndObjectNameMap.remove(contentKey));
//        }
//        for (String systemKey : WangEditorController.urlAndObjectNameMap.keySet()) {
//            system = system.replace(systemKey, WangEditorController.urlAndObjectNameMap.remove(systemKey));
//        }

        int result = 0;
        try {
            result = gameService.update(Game.builder().id(id).name(name).nickname(nickname).type(type).preprice(preprice).off(off)
                    .price(price).content(content).credit(credit).image(image).system(system)
                    .build());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 判断结果
        if (result == 1) {
            response.getWriter().print(JsonResult.builder().code(0).msg("修改成功").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("修改失败").build().toJsonString());
        }
    }


    //跳转到修改页面
    private void updatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        // 获取用户id
        Long id = Long.valueOf(request.getParameter("id"));

        // 调用service查询用户信息
        Game game = null;
        try {
            game = gameService.getOneById(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 转发到修改页面
        request.setAttribute("game", game);
        request.getRequestDispatcher("/game/update.jsp").forward(request, response);
    }


    //删除一条数据
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {


        // 获取id
        Long id = Long.valueOf(request.getParameter("id"));

        // 调用service删除数据
        int result = 0;
        try {
            result = gameService.delete(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断结果
        if (result == 1) {
            response.getWriter().print(JsonResult.builder().code(0).msg("删除成功").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
        }
    }


    //游戏详情
    private void detailGame(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取游戏id
        Long id = Long.valueOf(request.getParameter("id"));

        // 根据id查询游戏信息
        Game game = null;
        try {
            game = gameService.getOneById(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 转发到详情页面
        request.setAttribute("game", game);
        request.getRequestDispatcher("/game/detailGame.jsp").forward(request, response);
    }


    //表头删除数据
    private void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取id数组的json字符串
        String idsJson = request.getParameter("ids");
        // 将json字符串转为List集合
        List<Long> ids = JSON.parseArray(idsJson, Long.class);

        // 调用service删除所有数据
        int result = gameService.deleteAll(ids);

        // 判断结果
        if (ids.size() == result) {
            response.getWriter().print(JsonResult.builder().code(0).msg("全部删除成功").build().toJsonString());
        } else if (result != 0) {
            response.getWriter().print(JsonResult.builder().code(0).msg("成功删除" + result + "条，失败" + (ids.size() - result) + "条").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
        }
    }


    //添加游戏
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 获取请求参数
        String name = request.getParameter("name");
        String nickname = request.getParameter("nickname");
        GameTypeEnum type = GameTypeEnum.valueOf(request.getParameter("type"));
        Double preprice = Double.valueOf(request.getParameter("preprice"));
        Integer off = Integer.valueOf(request.getParameter("off"));
        Double price = Double.valueOf(request.getParameter("price"));
        String content = request.getParameter("content");
        Long credit = Long.valueOf(request.getParameter("credit"));
        String image = request.getParameter("image");
        String system = request.getParameter("system");
        Long publisher_id = Long.valueOf(request.getParameter("publisher_id"));


        // 将富文本内容中的src地址替换为objectName
//        for (String contentKey : WangEditorController.urlAndObjectNameMap.keySet()) {
//            content = content.replace(contentKey, WangEditorController.urlAndObjectNameMap.remove(contentKey));
//        }
//        for (String systemKey : WangEditorController.urlAndObjectNameMap.keySet()) {
//            system = system.replace(systemKey, WangEditorController.urlAndObjectNameMap.remove(systemKey));
//        }

        int result = 0;
        try {
            result = gameService.add(Game.builder().name(name).nickname(nickname).type(type).preprice(preprice).off(off)
                    .price(price).content(content).credit(credit).image(image).system(system)
                    .publisher_id(publisher_id).build());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 判断结果
        if (result == 1) {
            response.getWriter().print(JsonResult.builder().code(0).msg("添加成功").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("添加失败").build().toJsonString());
        }
    }

    // 获取游戏数据列表
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取分页参数
        Integer page = Integer.valueOf(request.getParameter("page"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));

        // 获取排序参数和排序方式
        String orderField = request.getParameter("orderField");
        String orderType = request.getParameter("orderType");

        // 获取条件查询参数
        String name = request.getParameter("name");
        String minprice = request.getParameter("minprice");
        String maxprice = request.getParameter("maxprice");
        String typeStr = request.getParameter("type");
        GameTypeEnum type = null;
        if (StringUtils.isNotBlank(typeStr)) {
            type = GameTypeEnum.valueOf(typeStr);
        }
        // 封装dto
        GameDto gameDto = GameDto.builder()
                .page(page).limit(limit).orderField(orderField)
                .orderType(orderType).name(name)
                .type(type).build();

        if (minprice != null && !minprice.equals("") && maxprice != null && !maxprice.equals("")) {
            gameDto.setMinprice(Integer.valueOf(minprice));
            gameDto.setMaxprice(Integer.valueOf(maxprice));
        }


        // 获取发帖时间区间字符串
        String createTimeRange = request.getParameter("createTimeRange");
        if (createTimeRange != null && createTimeRange.contains(" - ")) {
            String[] createTimeArray = createTimeRange.split(" - ");
            try {
                gameDto.setCreateTimeStart(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[0]));
                gameDto.setCreateTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[1]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 调用service获取帖子数据
        List<Game> list = null;
        try {
            list = gameService.list(gameDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 调用service获取帖子总数据量
        Long count = null;
        try {
            count = gameService.count(gameDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断结果
        if (list == null || count == null) {
            response.getWriter().print(JsonResult.builder().code(1).msg("查询错误").build().toJsonString());
            return;
        }

        // 封装结果返回
        response.getWriter().print(JsonResult.builder().code(0).count(count).data(list).build().toJsonString());

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
